package com.gpj.sqlbuilder.utils;

import org.apache.commons.lang3.StringUtils;
import sun.net.www.protocol.jar.JarURLConnection;

import java.io.File;
import java.net.URLConnection;
import java.util.jar.JarFile;

/**
 * @className JarIOUtil
 * @description
 *   TODO
 * @author GPJ
 * @date 2023-05-22 13:56
 * @version 1.0
 **/
public class JarIOUtil {
	public static String getJarInnerPath() {
		try {
			URLConnection connection = JarIOUtil.class.getProtectionDomain().getCodeSource().getLocation().openConnection();
			assert connection instanceof JarURLConnection;
			JarFile jarFile = ((JarURLConnection) connection).getJarFile();
			String path = jarFile.getName();
			int separator = path.indexOf("!/");
			return separator > 0 ? path.substring(0, separator) : path;
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("获取jar包内路径失败");
		}
	}

	private static File getJar() {
		try {
			String path = JarIOUtil.class.getProtectionDomain().getCodeSource().getLocation().getFile();
			// 转换处理中文及空格
			path = java.net.URLDecoder.decode(path, "UTF-8");
			assert StringUtils.isNotBlank(path);
			return new File(path);
		} catch (Exception e) {
			throw new RuntimeException("获取jar包路劲失败");
		}
	}

	/**
	 * 获取jar绝对路径
	 *
	 * @return
	 */
	public static String getJarPath() {
		return getJar().getAbsolutePath();
	}

	/**
	 * 获取jar目录
	 *
	 * @return
	 */
	public static String getJarDir() {
		return getJar().getParent();
	}
}
